import React, { useEffect, useState } from 'react'
import SyntaxHighlighter from 'react-syntax-highlighter'
import { atomOneDark as hlStyle } from 'react-syntax-highlighter/dist/esm/styles/hljs'
// atomOneDark agate androidstudio atelierDuneDark
import styles from './index.module.less'

export default function CodeBlock({ className, children }) {
  // console.log(className)
  const [language, setLanguage] = useState('java')
  const [lineNumbers, setLineNumbers] = useState([])

  useEffect(() => {
    getLineNumbers()
    getLanguage()
  }, [className, children])

  // 获取 语言
  const getLanguage = () => {
    const str = !className ? '' : className.split('-')[1]
    if (!str) return
    if (str == 'js') return setLanguage('javascript')
    setLanguage(str)
  }

  // 获取行号
  const getLineNumbers = () => {
    const lines = children[0].split('\n').length
    const lineNumbers = [...Array(lines).keys()]
    setLineNumbers([...lineNumbers])
  }

  return (
    <div className={styles.codeBlock}>
      <div className={styles.line_numbers}>
        {lineNumbers.map((i) => (
          <span key={i} className={styles.line_number}>
            {i + 1}
          </span>
        ))}
      </div>

      <div className={styles.code}>
        <SyntaxHighlighter
          language={language}
          style={hlStyle}
          customStyle={{ margin: '1em 0', fontSize: '18px' }}
        >
          {children[0]}
        </SyntaxHighlighter>
      </div>
    </div>
  )
}
